package com.diy.sigmund.diyorder.test.controller;

import com.diy.sigmund.diycommon.entity.CustomUser;
import com.diy.sigmund.diycommon.entity.ResultMsg;
import com.diy.sigmund.diycommon.spring.ContextHolder;
import com.diy.sigmund.diycommon.spring.CustomApplicationContext;
import com.diy.sigmund.diycommon.spring.anno.IgnoreTokenVerification;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author ylm-sigmund
 * @since 2022/6/18 15:30
 */
@RestController
public class ThreadLocalController {

    private static final Logger log = LoggerFactory.getLogger(ThreadLocalController.class);

    @PostMapping("/order/threadLocal")
    @IgnoreTokenVerification
    public ResultMsg threadLocal(@RequestBody CustomUser customUser) throws InterruptedException {
        ContextHolder.getInstance().setCustomUser(customUser);
        log.info("主线程打印信息:{}", customUser);
        CustomApplicationContext.getBean(ThreadLocalController.class).testPrint();
        CustomApplicationContext.getBean(ThreadLocalController.class).testPrint();
        CustomApplicationContext.getBean(ThreadLocalController.class).testPrint();
        return ResultMsg.success();
    }

    @Async("customAsyncExecutor")
    public void testPrint() throws InterruptedException {
        TimeUnit.SECONDS.sleep(5);
        log.info("测试threadLocal变量副本在父子线程传递");
        CustomUser customUser = ContextHolder.getInstance().getCustomUser();
        log.info("异步线程打印信息:{}", customUser);
    }
}
